import XLSX from 'xlsx';
import MtGrabTaskService from '../../api';
import CommonUtils from '../../CommonUtils';
import { MessageBox, Message, Loading } from 'element-ui';

export default {
  name: 'AddWeiziTask',
  data() {
    var checkStore = (rule, value, callback) => {
      if (this.storeCityList.length <= 0) {
        return callback(new Error('请上传门店数据'));
      }
      callback();
    };

    return {
      options: [
        {
          value: 'MTWM',
          label: 'MTWM',
        },
        {
          value: 'ELM',
          label: 'ELM',
        },
      ],
      propFalse: false,
      loading: false,
      addWeiziTaskTitle: '新增微子任务',
      windowModal: false,
      fileList: [],
      storeCityList: [],
      platformCode: 'MTWM',
      storeCityListShow: [],
      showFileList: false,
      level: 1,
      beginTime: CommonUtils.getCurrentTime(),
      rules: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          {
            min: 3,
            max: 30,
            message: '长度在 3 到 30 个字符',
            trigger: 'blur',
          },
        ],
        storeCityList: [{ required: true, validator: checkStore, trigger: 'blur' }],
      },
    };
  },
  props: {
    addWzTaskVisible: {
      type: Boolean,
      required: true,
      default: function() {
        return false;
      },
    },
    taskForm: {
      type: Object,
      default: function() {
        return {
          taskName: '',
        };
      },
    },
  },
  methods: {
    closeWeiziDialog() {
      this.$emit('closeWeiziTaskWindow');
    },
    beforeUpload(file) {
      let _this = this;
      // 使返回的值变成Promise对象，如果校验不通过，则reject，校验通过，则resolve
      // readExcel方法也使用了Promise异步转同步，此处使用then对返回值进行处理
      _this.readExcel(file);
    },
    async readExcel(file) {
      // let _this = this;
      const reader = new FileReader();
      reader.onload = e => {
        // 异步执行
        try {
          // 以二进制流方式读取得到整份excel表格对象
          let data = e.target.result,
            workbook = XLSX.read(data, { type: 'binary' });
          var sheetNames = workbook.SheetNames; // 工作表名称集合
          var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
          var sheetJson = XLSX.utils.sheet_to_json(worksheet);

          var scl = [];
          // 去重
          var storeName = [];
          for (let index in sheetJson) {
            let row = {};
            row.city = sheetJson[index].城市;
            row.storeName = sheetJson[index].门店名称;
            if (!storeName.includes(row.city + row.storeName)) {
              storeName.push(row.city + row.storeName);
              scl.push(row);
            } else {
              console.log('重复项：', row);
            }
          }
          // 最多100条记录
          if (scl.length > 100) {
            this.storeCityList = [];
            this.storeCityListShow = [];
            Message({
              type: 'error',
              duration: 5000,
              message: '一批最多支持100个门店的爬取，请重新导入！',
            });
            return;
          }

          this.storeCityList = scl;
          // 部分显示
          if (scl.length > 20) {
            let endIndex = scl.length <= 20 ? scl.length : 20;
            this.storeCityListShow = scl.slice(0, endIndex);
            this.storeCityListShow.push({
              city: '......',
              storeName: '......',
            });
          } else {
            this.storeCityListShow = scl;
          }
        } catch (e) {
          console.log(e);
        }
      };
      reader.readAsBinaryString(file);
    },
    selfHttpRequest() {
      console.log('selfHttpRequest');
    },
    async publishWeiziTask(formName) {
      this.loading = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.confirmSubmtForm();
        } else {
          console.log(valid, 'error submit!!');
          return false;
        }
      });
      this.loading = false;
    },
    async submitForm() {
      let loading = Loading.service({
        lock: true,
        text: '提交中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      let subTaskList = [];
      this.storeCityList.forEach(elem => {
        let subTask = {};
        subTask.storeName = elem.storeName;
        subTask.cityName = elem.city;
        subTask.taskType = 'WEIZI';
        subTask.level = this.level;
        subTask.beginTime = this.beginTime;
        subTask.platformCode = this.platformCode;
        subTaskList.push(subTask);
      });
      this.taskForm.crawlerSubTaskList = subTaskList;
      this.taskForm.taskType = 'WEIZI';
      this.taskForm.platformCode = this.platformCode;
      await MtGrabTaskService.batchPublishTask({ crawlerTask: this.taskForm });
      this.closeWeiziDialog();
      loading.close();
      Message({
        type: 'success',
        message: '任务创建成功!',
      });
    },
    async confirmSubmtForm() {
      MessageBox.confirm('确定提交' + this.storeCityList.length + '个（已去重）门店爬取任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.submitForm();
        })
        .catch(() => {});
    },
  },
};
